
bt.module({builder: function(bt) {
    var j$ = jQuery;
    var map;
    var currentMarker;
    var latlngbounds;
    var info_windows = {};
    var markers = {};
    var index = -1;
    var rotate = 0;
    var current_rotate = 0;

    var initDatepicker = function() {
        j$.datepicker.regional['zh-CN'] = {
            closeText: '关闭',
            prevText: '&#x3c;上月',
            nextText: '下月&#x3e;',
            currentText: '今天',
            monthNames: ['一月','二月','三月','四月','五月','六月',
            '七月','八月','九月','十月','十一月','十二月'],
            monthNamesShort: ['一','二','三','四','五','六',
            '七','八','九','十','十一','十二'],
            dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
            dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
            dayNamesMin: ['日','一','二','三','四','五','六'],
            weekHeader: '周',
            dateFormat: 'yy-mm-dd',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: true,
            yearSuffix: '年'};
        j$.datepicker.setDefaults(j$.datepicker.regional['zh-CN']);
        j$("input.date").datepicker({
            yearRange: "-20:+0",
            changeYear: true
        });
    };

    function popup(new_index) {
        if (index >= 0)
            info_windows[index].close();
        else if (map.getZoom() < 14)
            map.setZoom(14);
        info_windows[new_index].open(map, markers[new_index]);
        index = new_index;
    }

    function addWaypoint(i, data, type) {
        var image;
        var contentString = '';
        var prefix = '<div id="map_popup">';
        var postfix = '<p><a class="right-here" href="javascript:;">就在这里</a></p></div>';
        if (type == "start") {
            image = new google.maps.MarkerImage(STATIC_URL+'img/icon_new_start.png',
                new google.maps.Size(35, 37),
                new google.maps.Point(0, 0),
                new google.maps.Point(15, 34));
            contentString = prefix + '<p class="start">游记起点</p>' + postfix;
        } else if (type == "photo") {
            image = new google.maps.MarkerImage(STATIC_URL+'img/icon_new_photo.png',
                new google.maps.Size(35, 37),
                new google.maps.Point(0, 0),
                new google.maps.Point(15, 34));
            contentString = prefix + '<a href="#wp' + data[2] + '"><img width="180" height="135" src="' + data[1] + '" /></a>' + postfix;
            $('#wp' + data[2]).attr('lat', data[0].lat())
            $('#wp' + data[2]).attr('lng', data[0].lng())
        } else if (type == "text") {
            image = new google.maps.MarkerImage(STATIC_URL+'img/icon_new_text.png',
                new google.maps.Size(35, 37),
                new google.maps.Point(0, 0),
                new google.maps.Point(15, 34));
            contentString = prefix + '<a class="text" href="#wp' + data[2] + '">"' + data[1] + '"</a>' + postfix;
            $('#wp' + data[2]).attr('lat', data[0].lat())
            $('#wp' + data[2]).attr('lng', data[0].lng())
        }

        var marker = new google.maps.Marker({
            position: data[0],
            map: map,
            icon: image
        });
        markers[i] = marker;

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        google.maps.event.addListener(infowindow, 'domready', function() {
            j$(".right-here").click(function() {
                var pos = markers[i].getPosition();
                placeMarker(map, pos.lat(), pos.lng());
            });
        });

        info_windows[i] = infowindow;

        google.maps.event.addListener(marker, 'click', function() {
            popup(i);
        });
    }

    function getData(point) {
        var items = point.children();
        var lat = parseFloat($(items[0]).text());
        var lon = parseFloat($(items[1]).text());
        var content = $(items[2]).text();
        var wp_id = null;
        if (items.length > 3)
            wp_id = $(items[3]).text();
        return [new google.maps.LatLng(lat, lon), content, wp_id];
    }

    var searchAddress = function() {
        $('.pos-search input').blur();
        var address = $('.pos-search input').val();
        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                if (map.getZoom() < 14)
                    map.setZoom(14);
            } else {
                alert("未找到相关位置，修改搜索条件再试试？");
            }
        });
    };

    var updateMarkerLocation = function() {
        var latlng = currentMarker.getPosition();
        $('#latitude').val(latlng.lat());
        $('#longitude').val(latlng.lng());
    };

    var placeMarker = function(map, lat, lng) {
        if (currentMarker) {
            currentMarker.setMap(null);
        }

        currentMarker= new google.maps.Marker({
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: new google.maps.LatLng(lat, lng), 
            map: map
        });

        updateMarkerLocation();
        google.maps.event.addListener(currentMarker, 'dragend', updateMarkerLocation);
    };

    var initialize = function() {
        var options = {
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        map = new google.maps.Map(document.getElementById("map"), options);

        var points = $('#map_data').children();
        var coordinates = [];
        var latlngbounds = new google.maps.LatLngBounds();
        points.each(function(i, point) {
            point = $(point);
            var type = point.attr('class');
            data = getData(point);
            if (type != 'track')
                addWaypoint(i, data, type);
            coordinates.push(data[0]);
            latlngbounds.extend(data[0]);
        });

        var path = new google.maps.Polyline({
            path: coordinates,
            strokeColor: "#0695f8",
            strokeOpacity: 1.0,
            strokeWeight: 4
        });

        if (points.length > 1) {
            path.setMap(map);
        }

        var lat = $('#map').attr('lat');
        var lng = $('#map').attr('lng');
        var center_lat = $('#map').attr('map_lat');
        var center_lng = $('#map').attr('map_lng');
        if (lat && lng) {
            lat = parseFloat(lat);
            lng = parseFloat(lng);

            var latlng = new google.maps.LatLng(lat, lng);
            map.setCenter(latlng);
            map.setZoom(14);
            currentMarker= new google.maps.Marker({
                draggable: true,
                animation: google.maps.Animation.DROP,
                position: latlng,
                map: map
            });
            updateMarkerLocation();
            google.maps.event.addListener(currentMarker, 'dragend', updateMarkerLocation);
        } else if (center_lat && center_lng) {
            map.setCenter(new google.maps.LatLng(center_lat, center_lng));
            map.setZoom(14);
        } else {
            latlngbounds = new google.maps.LatLngBounds();

            latlngbounds.extend(new google.maps.LatLng(70, -180));
            latlngbounds.extend(new google.maps.LatLng(-30, 180));
            map.fitBounds(latlngbounds);
        }

        google.maps.event.addListener(path, 'click', function(event) {
            placeMarker(map, event.latLng.lat(), event.latLng.lng());
        });

        google.maps.event.addListener(map, 'click', function(event) {
            placeMarker(map, event.latLng.lat(), event.latLng.lng());
        });
        
        geocoder = new google.maps.Geocoder();
    };

    var _geocode = function(callback) {
        var lat = $('#latitude').val();
        var lng = $('#longitude').val();
        if (google && lat && lng) {
            var latlng = new google.maps.LatLng(lat, lng);
            geocoder.geocode(
                    {'latLng': latlng},
                    function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0] && results[0].address_components) {
                                var country_code, province, city;
                                for (var i in results[0].address_components)
                                    if ($.inArray('country', results[0].address_components[i].types) >= 0)
                                        country_code = results[0].address_components[i].short_name
                                    else if ($.inArray('administrative_area_level_1', results[0].address_components[i].types) >= 0)
                                        province = results[0].address_components[i].long_name
                                    else if ($.inArray('locality', results[0].address_components[i].types) >= 0)
                                        city = results[0].address_components[i].long_name
                                if (country_code) $('#country').val(country_code);
                                if (province) $('#province').val(province);
                                if (city) $('#city').val(city);
                                callback();
                            }
                        } else {
                            callback();
                        }
                    }
            );
        } else {
            callback();
        }
    };

    j$(document).ready(function() {
        // Auto move position
        j$('img.photo').bind('load', function(){
            bt.misc.centerAlignImg($(this), 130, 196);
        });

        bt.misc.centerAlignImg_x(j$("#edit-form .photo-cover .photo"), 130, 196);

        bt.gmap.initMapScript(initialize);
        initDatepicker();

        j$("form#edit-form .photo-file").change(function() {
            var filename = bt.misc.getFilename(this);
            j$("form#edit-form .filename").text(filename);
        });

        // Search position
        j$(".pos-search .search-btn").click(function() {
            searchAddress();
            return false;
        });

        j$('.pos-search input').keydown(function(e) {
            var code = e.which;
            if (code == 13) {
                searchAddress();
                e.preventDefault();
            }
        });
        
        j$(".done").click(function() {
            j$(".done").css("opacity", 0.3);
            _geocode(function() {
                j$("#edit-form").submit();
            });
            return false;
        });


        j$(".rotate-btn").click(function() {
            var popup = j$("#photo-rotate-popup");
            var overlay = $("#overlay");
            popup.fadeIn();
            overlay.show();
            var windowWidth = document.documentElement.clientWidth;
            var windowHeight = document.documentElement.clientHeight;
            var popupHeight = popup.height();
            var popupWidth = popup.width();
            popup.css({
                "position": "absolute",
                "top": windowHeight / 2 - popupHeight / 2
            });
            overlay.one("click", function() {
                popup.fadeOut();
                overlay.hide();
            });
            popup.find(".rotate-done").one("click", function() {
                popup.fadeOut();
                overlay.hide();
                j$("input#rotate").val(rotate);
                j$("#edit-form .photo-cover .photo").rotate(rotate * 90);
                bt.misc.centerAlignImg_x(j$("#edit-form .photo-cover .photo"), 130, 196);
            });
            bt.misc.centerAlignImg_r(
                false,
                j$("#photo-rotate-popup .photo"),
                j$("#photo-rotate-popup .photo").data("height"),
                j$("#photo-rotate-popup .photo").data("width"),
                435, 580);
        });

        var _rotate = function() {
            j$("#photo-rotate-popup .photo").toggleClass("normal rotated");
            bt.misc.centerAlignImg_r(
                false,
                j$("#photo-rotate-popup .normal"),
                j$("#photo-rotate-popup .photo").data("height"),
                j$("#photo-rotate-popup .photo").data("width"),
                435, 580);
            bt.misc.centerAlignImg_r(
                true,
                j$("#photo-rotate-popup .rotated"),
                j$("#photo-rotate-popup .photo").data("height"),
                j$("#photo-rotate-popup .photo").data("width"),
                435, 580);
            j$("#photo-rotate-popup .photo-img").rotate({animateTo: current_rotate});
        };

        j$(".rotate-left").click(function() {
            rotate = (rotate + 3) % 4;
            current_rotate -= 90;
            _rotate();
        });

        j$(".rotate-right").click(function() {
            rotate = (rotate + 1) % 4;
            current_rotate += 90;
            _rotate();
        });

    });
}});
